package com.unlcn.ils.wms.backend.webservice.client;

import cn.huiyunche.commons.exception.BusinessException;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.unlcn.ils.wms.backend.enums.SendStatusEnum;
import com.unlcn.ils.wms.backend.service.webservice.client.WmsJmCRMService;
import com.unlcn.ils.wms.backend.util.webservice.WebServiceSoapUtils;
import com.unlcn.ils.wms.backend.util.webservice.XmlParseUtils;
import com.unlcn.ils.wms.base.mapper.junmadcs.WmsCrmLogMapper;
import com.unlcn.ils.wms.base.mapper.junmadcs.WmsHandoverOrderExcpMapper;
import com.unlcn.ils.wms.base.mapper.junmadcs.WmsHandoverOrderMapper;
import com.unlcn.ils.wms.base.model.junmadcs.WmsCrmLogWithBLOBs;
import com.unlcn.ils.wms.base.model.junmadcs.WmsHandoverOrder;
import com.unlcn.ils.wms.base.model.junmadcs.WmsHandoverOrderExcp;
import com.unlcn.ils.wms.base.model.junmadcs.WmsHandoverOrderExcpExample;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringEscapeUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Service
public class WmsJmCRMServiceImpl implements WmsJmCRMService {

    private Logger LOGGER = LoggerFactory.getLogger(getClass());

    private static final int TOTAL_COUNT = 5;

    @Value("${wms.webservice.sap.host.url}")
    private String piHost;

    @Value("${wms.webservice.username}")
    private String username;

    @Value("${wms.webservice.password}")
    private String password;

    private WmsCrmLogMapper wmsCrmLogMapper;

    @Autowired
    public void setWmsCrmLogMapper(WmsCrmLogMapper wmsCrmLogMapper) {
        this.wmsCrmLogMapper = wmsCrmLogMapper;
    }

    private WmsHandoverOrderMapper wmsHandoverOrderMapper;

    @Autowired
    public void setWmsHandoverOrderMapper(WmsHandoverOrderMapper wmsHandoverOrderMapper) {
        this.wmsHandoverOrderMapper = wmsHandoverOrderMapper;
    }

    private WmsHandoverOrderExcpMapper wmsHandoverOrderExcpMapper;

    @Autowired
    public void setWmsHandoverOrderExcpMapper(WmsHandoverOrderExcpMapper wmsHandoverOrderExcpMapper) {
        this.wmsHandoverOrderExcpMapper = wmsHandoverOrderExcpMapper;
    }

    /**
     * 交接单webservice发送数据到crm 接口:   http://58.144.142.90:50000/dir/wsdl?p=sa/54b25fdde2a33089b0d06f10bc87921d
     *
     * @return
     * @throws Exception
     */
    @Override
    public void saveHandoverOrderToCRM(List<WmsHandoverOrder> handoverOrderList) throws Exception {
        LOGGER.info("WmsJmCRMServiceImpl.saveHandoverOrderToCRM param{}", handoverOrderList);
        //加入spring的上下文
        //SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext(this);
        SimpleDateFormat sdf_1 = new SimpleDateFormat("yyyy/MM/dd");
        StringBuilder soapXmlBuf = new StringBuilder();
        //xml头
        soapXmlBuf.append("<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:tem=\"http://tempuri.org/\">")
                .append("<soapenv:Header/>")
                .append("<soapenv:Body>")
                .append("<tem:IF_Crm2SAP_Vehicle_PGI>")
                .append("<tem:BODY>");
        //参数拼接
        for (WmsHandoverOrder wmsHandoverOrder : handoverOrderList) {
            if (StringUtils.isBlank(wmsHandoverOrder.getVbeln())) {
                throw new BusinessException("订单号为空");
            }
            if (wmsHandoverOrder.getPosnr() == null) {
                throw new BusinessException("订单行ID为空");
            }
            if (StringUtils.isBlank(wmsHandoverOrder.getZaction())) {
                throw new BusinessException("发运类型为空");
            }
            if (StringUtils.isBlank(wmsHandoverOrder.getLgort())) {
                throw new BusinessException("发货仓库CODE为空");
            }
            if (StringUtils.isBlank(wmsHandoverOrder.getMatnr())) {
                throw new BusinessException("物料编码为空");
            }
            if (StringUtils.isBlank(wmsHandoverOrder.getSernr())) {
                throw new BusinessException("车架号为空");
            }
            soapXmlBuf.append("<tem:VBELN>" + wmsHandoverOrder.getVbeln() + "</tem:VBELN>")//订单号
                    .append("<tem:POSNR>" + wmsHandoverOrder.getPosnr() + "</tem:POSNR>")//订单行ID
                    .append("<tem:ZACTION>" + wmsHandoverOrder.getZaction() + "</tem:ZACTION>")//发运类型
                    .append("<tem:LGORT>" + wmsHandoverOrder.getLgort() + "</tem:LGORT>")//发货仓库
                    .append("<tem:ZLGORT>" + wmsHandoverOrder.getZlgort() + "</tem:ZLGORT>")//调拨仓库
                    .append("<tem:MATNR>" + wmsHandoverOrder.getMatnr() + "</tem:MATNR>")//物料代码
                    .append("<tem:SERNR>" + wmsHandoverOrder.getSernr() + "</tem:SERNR>");//车架号
        }
        soapXmlBuf.append("</tem:BODY>")
                .append("</tem:IF_Crm2SAP_Vehicle_PGI>")
                .append("</soapenv:Body>")
                .append("</soapenv:Envelope>");
        String soapUrl = "http://" + piHost + "/XISOAPAdapter/MessageServlet?senderParty=&senderService=BC_WMS&receiverParty=&receiverService=&interface=SI_WMS2CRM_Vehicle_OUT&interfaceNamespace=http://zjunma.com/TRAUM/WMS/CRM";
        String soapHost = piHost;
        String soapAction = "http://sap.com/xi/WebService/soap/1.1";
        System.err.println(soapXmlBuf.toString());
        LOGGER.info("交接单CRM接口参数:", soapXmlBuf.toString());
        String result = WebServiceSoapUtils.postSoapToPi(soapUrl, soapHost, soapXmlBuf.toString(), soapAction, username, password);
        String xmlResult = StringEscapeUtils.unescapeHtml3(result);
        LOGGER.info("交接单CRM接口结果:", xmlResult);
        System.out.println(xmlResult);
        //记录日志
        String finalXmlResult = xmlResult;
        Runnable runnable = () -> {
            WmsCrmLogWithBLOBs log = new WmsCrmLogWithBLOBs();
            log.setParam(soapXmlBuf.toString());
            log.setMsgHead(null);
            log.setSendType("OUT");
            log.setResult(finalXmlResult);
            log.setGmtCreate(new Date());
            log.setGmtUpdate(new Date());
            log.setUrl("WmsJmCRMServiceImpl.saveHandoverOrderToCRM");
            wmsCrmLogMapper.insertSelective(log);
            LOGGER.info("WmsJmCRMServiceImpl.saveHandoverOrderToCRM  保存交接单发送CRM日志成功");
        };
        new Thread(runnable).start();
        //解析xml
        if (StringUtils.isNotBlank(xmlResult)) {
            Map<String, Object> objectMap = XmlParseUtils.xml2map(xmlResult);
            //获取返回结果
            String json = new Gson().toJson(objectMap);
            JSONObject jsonObject3 = JSONObject.parseObject(json);
            String code_str = jsonObject3.getString("Body");
            JSONObject jsonObject4 = JSONObject.parseObject(code_str);
            String returnCode_str = jsonObject4.getString("Body");
            JSONObject jsonObject = JSONObject.parseObject(returnCode_str);
            String if_str = jsonObject.getString("IF_Crm2SAP_Vehicle_PGIResponse");
            JSONObject jsonObject1 = JSONObject.parseObject(if_str);
            String body = jsonObject1.getString("BODY");
            JSONObject jsonObject2 = JSONObject.parseObject(body);
            String code = jsonObject2.getString("CODE");
            JSONObject jsonObject5 = JSONObject.parseObject(code);
            String code1 = jsonObject5.getString("CODE");

            String msg = jsonObject2.getString("MSG");
            JSONObject jsonObject6 = JSONObject.parseObject(msg);
            String msg1 = jsonObject6.getString("MSG");
            if (!"0".equals(code1)) {
                //返回失败
                WmsHandoverOrder wmsHandoverOrder = handoverOrderList.get(0);
                wmsHandoverOrder.setSendStatusCrm(SendStatusEnum.SEND_FAILED.getValue());
                wmsHandoverOrder.setGmtUpdate(new Date());
                wmsHandoverOrder.setResultMsgCrm(msg1);
                //查询接口异常表
                updateOrderOutExcpForCRM(wmsHandoverOrder);

            } else {
                //成功
                handoverOrderList.forEach((WmsHandoverOrder v) -> {
                    v.setGmtUpdate(new Date());
                    v.setResultMsgCrm("同步CRM接口成功");
                    v.setSendStatusCrm(SendStatusEnum.SEND_SUCCESS.getValue());
                    wmsHandoverOrderMapper.updateByPrimaryKeySelective(v);
                    //查询接口异常表
                    WmsHandoverOrderExcpExample excpExample = new WmsHandoverOrderExcpExample();
                    excpExample.createCriteria().andDataIdEqualTo(v.getDataId());
                    List<WmsHandoverOrderExcp> wmsHandoverOrderExcps = wmsHandoverOrderExcpMapper.selectByExample(excpExample);
                    if (CollectionUtils.isNotEmpty(wmsHandoverOrderExcps)) {
                        WmsHandoverOrderExcp wmsHandoverOrderExcp = wmsHandoverOrderExcps.get(0);
                        //写入成功
                        wmsHandoverOrderExcp.setResultMsgCrm("第" + wmsHandoverOrderExcp.getSendCountCrm() + "次同步CRM接口成功");
                        wmsHandoverOrderExcp.setFinalSendStatusCrm(SendStatusEnum.SEND_SUCCESS.getValue());
                        wmsHandoverOrderExcp.setGmtUpdate(new Date());
                        wmsHandoverOrderExcp.setSendStatusCrm(SendStatusEnum.SEND_SUCCESS.getValue());
                        wmsHandoverOrderExcpMapper.updateByPrimaryKeySelective(wmsHandoverOrderExcp);
                    }
                });
            }

        }
    }

    /**
     * 更新异常接口表数据
     *
     * @param order 订单
     */
    private void updateOrderOutExcpForCRM(WmsHandoverOrder order) {
        WmsHandoverOrderExcpExample excpExample = new WmsHandoverOrderExcpExample();
        excpExample.createCriteria().andDataIdEqualTo(order.getDataId());
        List<WmsHandoverOrderExcp> wmsHandoverOrderExcps = wmsHandoverOrderExcpMapper.selectByExample(excpExample);
        if (CollectionUtils.isEmpty(wmsHandoverOrderExcps)) {
            //往接口异常表里写入数据,
            WmsHandoverOrderExcp handoverOrderExcp = new WmsHandoverOrderExcp();
            BeanUtils.copyProperties(order, handoverOrderExcp);
            handoverOrderExcp.setSendCountCrm(1);
            handoverOrderExcp.setResultMsgCrm(order.getResultMsgCrm());
            handoverOrderExcp.setSendStatusCrm(SendStatusEnum.SEND_FAILED.getValue());
            handoverOrderExcp.setSendCountSap(1);
            handoverOrderExcp.setSendStatusSap(order.getSendStatusSap());
            handoverOrderExcp.setResultMsgSap(order.getResultMsgSap());
            handoverOrderExcp.setSendCountDcs(1);
            handoverOrderExcp.setSendStatus(order.getSendStatus());
            handoverOrderExcp.setResultMsgDcs(order.getResultMsgDcs());
            handoverOrderExcp.setGmtUpdate(new Date());
            handoverOrderExcp.setDataId(order.getDataId());
            wmsHandoverOrderExcpMapper.insertSelective(handoverOrderExcp);
        } else {
            WmsHandoverOrderExcp wmsHandoverOrderExcp = wmsHandoverOrderExcps.get(0);
            //增加调用次数
            if (wmsHandoverOrderExcp.getSendCountCrm() <= TOTAL_COUNT) {
                wmsHandoverOrderExcp.setSendStatusCrm(SendStatusEnum.SEND_FAILED.getValue());
                wmsHandoverOrderExcp.setGmtUpdate(new Date());
                if (wmsHandoverOrderExcp.getSendCountCrm() == TOTAL_COUNT) {//最后一次
                    wmsHandoverOrderExcp.setFinalSendStatusCrm(SendStatusEnum.SEND_FAILED.getValue());
                } else {
                    wmsHandoverOrderExcp.setSendCountCrm(wmsHandoverOrderExcp.getSendCountCrm() + 1);
                }
                wmsHandoverOrderExcp.setResultMsgCrm(order.getResultMsgCrm());
                wmsHandoverOrderExcpMapper.updateByPrimaryKeySelective(wmsHandoverOrderExcp);
            }
        }
    }

}
